package cn.hello2018.servlet;

import com.jspsmart.upload.SmartUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author jeymingwu
 * @date 2019/3/11 14:49
 */
public class SmartUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //设置上传文件保存路径
        String filePath = getServletContext().getRealPath("/") + "file";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }

        SmartUpload smartUpload = new SmartUpload();
        // 初始化对象
        smartUpload.initialize(getServletConfig(), req, resp);
        // 设置上传文件大小
        smartUpload.setMaxFileSize(1024 * 1024 * 100);
        // 设置所有文件的大小
        smartUpload.setTotalMaxFileSize(1024 * 1024 * 20 * 100);
        // 限制上传文件的类型
        smartUpload.setAllowedFilesList("txt,jpg,gif,doc,docx,mp4");
        String result = "上传成功！";
        try {
            // 设置禁止上传的文件类型
            smartUpload.setDeniedFilesList("rar,jsp,js");
            // 上传文件
            smartUpload.upload();
            int count = smartUpload.save(filePath);
            result += "上传了" + count + "份文件！";
        } catch (Exception e) {
            e.printStackTrace();
            result = "上传失败！";
            if (e.getMessage().indexOf("1015") != -1) {
                result += "上传文件类型不正确";
            } else if (e.getMessage().indexOf("1010") != -1) {
                result += "上传文件类型不正确";
            } else if (e.getMessage().indexOf("1105") != -1) {
                result += "上传文件大小大于允许上传的最大值！";
            } else if (e.getMessage().indexOf("1110") != -1) {
                result += "上传文件总大小大于允许上传总大小的最大值！";
            }
        }

        for (int i = 0; i < smartUpload.getFiles().getCount(); ++i) {
            com.jspsmart.upload.File tempFile = smartUpload.getFiles().getFile(i);
            System.out.println("-------------------------------------");
            System.out.println("1.表单中name的值：" + tempFile.getFieldName());
            System.out.println("2.上传文件名：" + tempFile.getFileName());
            System.out.println("3.上传文件的大小：" + tempFile.getSize());
            System.out.println("4.上传文件的拓展名：" + tempFile.getFileExt());
            System.out.println("5.上传文件全名" + tempFile.getFilePathName());
            System.out.println("-------------------------------------");
        }

        req.setAttribute("result", result);
        req.getRequestDispatcher("/jsp/uploadImageII.jsp").forward(req, resp);
    }
}
